import * as api from '../api/api';
import request from '../utils/request';
import { pageSize } from '../utils/common';

export default {
    namespace: 'commission',
    state: {
        commission: {},
        commissions: { totalCount: 0, items: [] },
        commissionsSearchs: { pageIndex: 1, pageSize},
    },
    effects: {
        /**
         * 获取佣金分配列表
         * @param param0 
         * @param param1 
         */
        *getCommissions({ payload }, { call, put }) {
            const {pageIndex, pageSize } = payload;
            const formSkipCount = (pageIndex - 1) * pageSize, formMaxResultCount = pageSize;
            const commissions: api.AbpApplicationServicesDtoPagedResultDtoSingleUserMallCommissionsVOCommissionVO =
                yield request(api.ManagecommissionManageApiFetchParamCreactor.managecommissionManageGetCommissionsAsync
                    ({
                        formSkipCount, formMaxResultCount
                    }))
            yield put({ type: 'save', payload: { commissions }, commissionsSearchs: { pageIndex, pageSize}  });
        },
        /**
         * 获取佣金详情
         * @param param0 
         * @param param1 
         */
        *getCommission({ payload }, { call, put }) {
            const formId = payload.id;
            const commission: api.SingleUserMallCommissionsVOCommissionVO =
                yield request(api.ManagecommissionManageApiFetchParamCreactor.managecommissionManageGetCommissionAsync({
                    formId,
                }))
            yield put({ type: 'save', payload: { commission } });
        },
        /**
         * 保存佣金
         * @param param0 
         * @param param1 
         */
        *saveCommission({ payload }, { call, put, select }) {
            const { form, callback } = payload;
            const { commissionsSearchs } = yield select(({ commission }) => commission);
            yield request(api.ManagecommissionManageApiFetchParamCreactor.managecommissionManageSaveCommissionAsync(
                { form }
            ));
            yield put({ type: 'getCommissions', payload: { ...commissionsSearchs }  });
            callback && callback(true);
        }
    },
    reducers: {
        save(state, action) {
            return { ...state, ...action.payload };
        },
    },
    subscriptions: {
        setup({ dispatch, history }) {
            return history.listen(({ pathname, search }) => {
                switch (pathname) {
                    case '/commission/commissions':
                        dispatch({ type: 'getCommissions', payload: { pageIndex: 1, pageSize } });
                        break;
                }
            });
        },
    },
};